<template>
  <el-card>
    <el-form :inline="true" :model="formInline" style="display: flex">
      <el-form-item>
        <el-input v-model="formInline.roleName" placeholder="名称" />
      </el-form-item>
      <el-form-item style="width: 100px">
        <el-select v-model="formInline.status" clearable placeholder="状态">
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item style="flex:1">
        <el-date-picker
            v-model="during"
            type="daterange"
            range-separator="到"
            start-placeholder="创建开始时间"
            end-placeholder="创建结束时间"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchRoles()">查询</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card>
    <el-button type="primary" @click="showAddModal">添加角色</el-button>
    <el-button type="primary" @click="showUploadModal">数据导入</el-button>
    <el-button type="primary" @click="exportData">数据导出</el-button>
    <el-popconfirm title="确认删除?" @confirm="batchDeleteRole">
      <template #reference>
        <el-button type="danger">批量删除</el-button>
      </template>
    </el-popconfirm>
    <el-table :data="roles" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="roleId" label="ID" width="100"></el-table-column>
      <el-table-column prop="roleName" label="名称" align="center"></el-table-column>
      <el-table-column prop="description" label="描述" align="center"></el-table-column>
      <el-table-column align="center" prop="createTime" label="创建时间"></el-table-column>
      <el-table-column align="center" prop="updateTime" label="更新时间"></el-table-column>
      <el-table-column align="center" prop="status" label="状态">
        <template #default="{ row }">
          <el-radio-group v-model="row.status" is-button size="small" @change="updateRoleStatus(row)">
            <el-radio-button :label="i.label" :value="i.value" v-for="i in options"/>
          </el-radio-group>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="200px">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="showPermissionModal(row)">权限</el-button>
          <el-button type="primary" size="small" @click="showEditModal(row)">编辑</el-button>
          <el-popconfirm title="确认删除?" @confirm="deleteRole(row.roleId)">
            <template #reference>
              <el-button type="danger" size="small">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100, 1000, 5000]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </el-card>

  <!-- 添加角色模态框 -->
  <el-dialog v-model="addDialogVisible" title="添加角色">
    <el-form ref="addFormRef" :model="addFormData" label-width="80px" :rules="rules">
      <el-form-item label="名称" prop="roleName">
        <el-input v-model="addFormData.roleName"></el-input>
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="addFormData.description"></el-input>
      </el-form-item>
      <el-form-item label="权限">
        <el-tree style="border: 1px solid rgba(0,0,0,.1); width:100%;"
            :data="permissionList"
            multiple
            show-checkbox
            node-key="permissionId"
            :props="{ label: 'permissionName', children: 'children', value: 'permissionId'}"
             ref="addTreeRef"
        />
      </el-form-item>

    </el-form>
    <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addRole(addFormRef)">确定</el-button>
        </span>
    </template>
  </el-dialog>

  <!-- 导入数据 -->
  <el-dialog v-model="uploadDialogVisible" title="导入数据">
    <el-upload class="upload-demo" drag :action="uploadURL" multiple :on-success="handleUploadSuccess">
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">拖拽文件到此处或者点击上传</div>
    </el-upload>
  </el-dialog>

  <!-- 编辑角色模态框 -->
  <el-dialog v-model="editDialogVisible" title="编辑角色">
    <el-form ref="editFormRef" :model="editFormData" label-width="80px" :rules="rules">
      <el-form-item label="名称" prop="roleName">
        <el-input v-model="editFormData.roleName"></el-input>
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="editFormData.description"></el-input>
      </el-form-item>
      <el-form-item label="状态">
        <el-radio-group v-model="editFormData.status" is-button>
          <el-radio-button :label="i.label" :value="i.value" v-for="i in options"/>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelUpdateRole()">取消</el-button>
          <el-button type="primary" @click="updateRole(editFormRef)">确定</el-button>
        </span>
    </template>
  </el-dialog>

  <!-- 编辑权限模态框 -->
  <el-dialog v-model="permissionDialogVisible" title="编辑角色权限">
    <el-form label-width="80px">
      <el-form-item label="权限">
        <el-tree style="border: 1px solid rgba(0,0,0,.1); width:100%;"
                 :data="permissionList"
                 multiple
                 show-checkbox
                 :default-expand-all="true"
                 node-key="permissionId"
                 :default-checked-keys="defaultCheckedKeys"
                 :props="{ label: 'permissionName', children: 'children', value: 'permissionId'}"
                 ref="editTreeRef"
        />
      </el-form-item>
    </el-form>
    <template #footer>
        <span class="dialog-footer">
          <el-button @click="permissionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updatePermission()">确定</el-button>
        </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { fetchRolePage, postRole, putRole, delRole, batchDelRole, exportRoleData, fetchRolePermission, putRolePermission } from "@/api/RoleApi.ts";
import type { ElMessage, UploadProps, FormInstance, FormRules } from 'element-plus';
import { UploadFilled } from "@element-plus/icons-vue";
import {Permission, Role} from "@/api/type/model.ts";
import {useRouter} from "vue-router";
import {fetchPermissionTree} from "@/api/PermissionApi.ts";

const roles: Role[] = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const addDialogVisible = ref(false);
const editDialogVisible = ref(false);
const permissionDialogVisible = ref(false)
const multipleSelection = ref<Role[]>([]);
const uploadDialogVisible = ref(false);
const uploadURL = ref(import.meta.env.VITE_APP_BASE_FILE_API);
let addFormData: Role = reactive({});
let editFormData: Role = reactive({});
const addFormRef = ref<FormInstance>();
const editFormRef = ref<FormInstance>();
const router = useRouter()
const permissionList: Permission[] = ref([]);
const defaultCheckedKeys= ref([])
const addTreeRef = ref()
const editTreeRef = ref()
const roleId = ref(0);

const rules = reactive<FormRules>({
  roleName: [
    { required: true, trigger: 'blur' },
    { min: 1, max: 100, message: '字数必须为 1 到 100', trigger: 'blur', informType: 'warning' },
  ],
  description: [
    { required: true, trigger: 'blur' },
    { min: 1, max: 100, message: '字数必须为 1 到 100', trigger: 'blur', informType: 'warning' },
  ]
});

const formInline: Role = reactive({});

const during = ref([])

const options = ref([
  { value: '1', label: '正常' },
  { value: '0', label: '禁用' }
]);

const fetchRoles = async () => {
  const response = await fetchRolePage(currentPage.value, pageSize.value, formInline, during.value);
  roles.value = response.data.records;
  total.value = response.data.total;
};

const addRole = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid) => {
    if (!valid) {
      return;
    }
    const res = await postRole(addFormData, addTreeRef.value.getCheckedKeys());
    if (res.code === 200){
      addDialogVisible.value = false;
      await fetchRoles();
    }
  });
};


const fetchPermission = async () => {
  const response = await fetchPermissionTree();
  permissionList.value = JSON.parse(JSON.stringify(response.data))
};

const cancelUpdateRole = () => {
  editDialogVisible.value = false;
  fetchRoles();
};

const updateRole = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid) => {
    if (!valid) {
      return;
    }
    await putRole(editFormData);
    editDialogVisible.value = false;
    await fetchRoles();
  });
};

const updateRoleStatus = async (role: Role) => {
  await putRole(role);
  editDialogVisible.value = false;
  await fetchRoles();
};

const deleteRole = async (roleId: number) => {
  await delRole(roleId);
  await fetchRoles();
};

const showAddModal = () => {
  addFormRef.value?.resetFields();
  addDialogVisible.value = true;
  fetchPermission()
};

const showEditModal = async (row: Role) => {
  editFormRef.value?.resetFields();
  editFormData = row;
  editDialogVisible.value = true;
  fetchPermission()
};

const showPermissionModal = async (row: Role) => {
  roleId.value = row.roleId;
  addFormRef.value?.resetFields();
  permissionDialogVisible.value = true;
  fetchPermission()
  const res = await fetchRolePermission(row.roleId)
  if(res.data){
    defaultCheckedKeys.value = res.data.map((permission: Permission) => permission.permissionId)
  }
};

const handleCurrentChange = (newPage: number) => {
  currentPage.value = newPage;
  fetchRoles();
};

const handleSizeChange = (newSize: number) => {
  pageSize.value = newSize;
  fetchRoles();
};

// 多选
const handleSelectionChange = (val: Role[]) => {
  multipleSelection.value = val;
}

// 批量删除
const batchDeleteRole = async () => {
  let roleIds: number[] = multipleSelection.value.map((role: Role) => role.roleId);
  if (roleIds.length === 0) {
    return ElMessage.error("请先选中！");
  }
  await batchDelRole(roleIds);
  await fetchRoles();
}

// 数据导入
const showUploadModal = () => {
  uploadDialogVisible.value = true;
}
const handleUploadSuccess: UploadProps['onSuccess'] = () => {
  ElMessage.success("导入成功");
  uploadDialogVisible.value = false;
  fetchRoles();
}

// 导出数据
const exportData = async () => {
  const res = await exportRoleData();
  const blob = new Blob([res.data]);
  let url = window.URL.createObjectURL(blob);
  let link = document.createElement("a");
  link.href = url;
  link.setAttribute('download', formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss') + ".csv");
  document.body.appendChild(link);
  link.click();
}

const updatePermission = async () => {
  const res = await putRolePermission(roleId.value,editTreeRef.value.getCheckedKeys());
  if(res.code === 200){
    permissionDialogVisible.value = false;
  }
}

fetchRoles();

</script>

<style scoped>
.el-card {
  margin-top: 20px;
  border: 1px solid rgba(0, 0, 0, 0.2);
  box-shadow: 0 0 0 #ffffff;
  outline: 0;
}
</style>

